/*
 * @Author: szx
 * @Date: 2021-10-09 18:25:03
 * @LastEditTime: 2021-10-09 19:13:45
 * @Description:
 * @FilePath: \leetcode\482\482.go
 */
package main

import (
	"bytes"
	"fmt"
	"strings"
)

func licenseKeyFormatting(s string, k int) string {
	s1 := strings.Replace(s, "-", "", -1)
	s1 = strings.ToUpper(s1)
	length := len(s1)
	if length <= k {
		return s1
	}
	var buffer bytes.Buffer
	first := length % k
	if first == 0 {
		length -= 1
		buffer.WriteString(s1[0:k])
		first += k
	} else {
		buffer.WriteString(s1[0:first])
	}
	var num int = length / k

	start := first
	for i := 0; i < num; i++ {
		buffer.WriteString("-")
		buffer.WriteString(s1[start : start+k])
		start += k
	}
	return buffer.String()
}

func main() {
	fmt.Println(licenseKeyFormatting("5F3Z-2e-9-w", 4))
	fmt.Println(licenseKeyFormatting("2-5G-3J", 2))
	fmt.Println(licenseKeyFormatting("2", 2))
}
